<template>
  <div class="multi-spec-container">
    <!-- 规格管理区域 -->
    <div class="spec-management">
      <el-button type="primary" @click="addSpec" size="small">添加规格</el-button>

      <div v-for="(spec, specIndex) in internalSpecs" :key="spec.id || specIndex" class="spec-item">
        <div class="spec-header">
          <el-input v-model="spec.name" placeholder="规格名称" style="width: 200px; margin-right: 10px;"
            @change="validateSpecName(specIndex)"></el-input>
          <span v-if="spec.id" style="margin-right: 10px;">ID: {{spec.id}}</span>

          <el-button @click="addSpecValue(specIndex)" size="mini" icon="el-icon-plus">添加规格值</el-button>
          <el-button @click="removeSpec(specIndex)" size="mini" type="danger" icon="el-icon-delete"></el-button>
        </div>

        <div class="spec-values">
          <draggable v-model="spec.values" handle=".drag-handle">
            <div v-for="(value, valueIndex) in spec.values" :key="valueIndex" class="spec-value-item">
              <el-input
                v-model="spec.values[valueIndex]"
                placeholder="规格值"
                style="width: 150px; margin-right: 10px;"
                @change="validateSpecValue(specIndex, valueIndex)"
                @blur="handleSpecValueBlur(specIndex, valueIndex)">
              </el-input>

              <span v-if="spec.rawValues && spec.rawValues[valueIndex] && spec.rawValues[valueIndex].id"
                style="margin-right: 10px;">
                ID: {{spec.rawValues[valueIndex].id}}
              </span>

              <img v-if="spec.images && spec.images[value]" :src="spec.images[value]" class="spec-image-preview">

              <el-upload class="spec-value-upload" :action="imgUploadUrl" :show-file-list="false"
                :on-success="(res, file) => handleSpecImageSuccess(res, file, specIndex, valueIndex)">
                <el-button size="mini">上传图片</el-button>
              </el-upload>
              <i class="el-icon-rank drag-handle" style="margin: 0 10px; cursor: move;"></i>
              <el-button @click="removeSpecValue(specIndex, valueIndex)" size="mini" type="danger" icon="el-icon-delete"
                circle></el-button>
            </div>
          </draggable>
        </div>
      </div>
    </div>

    <!-- 生成SKU按钮 -->
    <div class="generate-sku">
      <el-button type="primary" @click="generateSkus" :disabled="!canGenerateSkus"
        :loading="generatingSkus">生成SKU列表</el-button>

      <el-button v-if="skus.length > 0" @click="batchSetPrice" size="small">批量设置价格</el-button>
      <el-button v-if="skus.length > 0" @click="batchSetMarketPrice" size="small">批量设置划线价格</el-button>
      <el-button v-if="skus.length > 0" @click="batchSetStock" size="small">批量设置库存</el-button>

      <el-button type="warning" @click="resetData" size="small" :disabled="!canReset">重置数据</el-button>
    </div>

    <!-- SKU表格 -->
    <div class="sku-table" v-if="skus.length > 0">
      <el-table :data="skus" border style="width: 100%" size="small">
        <!-- ID列 -->
        <el-table-column label="ID" width="100" v-if="skus.some(s => s.id)">
          <template slot-scope="scope">
            {{scope.row.id || '新增'}}
          </template>
        </el-table-column>

        <!-- 规格列 -->
        <el-table-column v-for="(spec, specIndex) in internalSpecs" :key="specIndex" :label="spec.name" width="150">
          <template slot-scope="scope">
            {{ scope.row.spec_values ? scope.row.spec_values[specIndex] : '' }}
          </template>
        </el-table-column>

        <!-- 价格列 -->
        <el-table-column label="* 价格(元)" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.price" :min="0" :precision="2" controls-position="right"
              size="mini"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="* 划线价格(元)" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.market_price" :min="0" :precision="2" controls-position="right"
              size="mini"></el-input-number>
          </template>
        </el-table-column>

        <!-- 库存列 -->
        <el-table-column label="* 库存" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.stock" :min="0" controls-position="right" size="mini"></el-input-number>
          </template>
        </el-table-column>

        <!-- SKU编码 -->
        <el-table-column label="SKU编码" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.code" placeholder="自动生成" size="mini"
              @change="generateSkuCode(scope.row)"></el-input>
          </template>
        </el-table-column>

        <!-- 重量 -->
        <el-table-column label="重量" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.weight" :min="0" controls-position="right"
              size="mini"></el-input-number>
          </template>
        </el-table-column>

        <!-- 图片 -->
        <el-table-column label="* 图片" width="150">
          <template slot-scope="scope">
            <el-upload class="sku-image-upload" :action="imgUploadUrl" :show-file-list="false"
              :on-success="(res, file) => handleSkuImageSuccess(res, file, scope.$index)">
              <img v-if="scope.row.image" :src="scope.row.image" class="sku-image">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="removeSku(scope.$index)" type="danger" size="mini" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量设置对话框 -->
          <el-dialog :title="batchDialog.title" :visible.sync="batchDialog.visible" width="30%">
            <el-form>
              <el-form-item :label="batchDialog.label">
                <el-input-number v-model="batchDialog.value" :min="0" :precision="batchDialog.precision"></el-input-number>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="batchDialog.visible = false">取 消</el-button>
              <el-button type="primary" @click="confirmBatchSet">确 定</el-button>
            </span>
          </el-dialog>

      <el-button type="primary" @click="submitData" class="bt-fix"> 下一步 </el-button>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: {
    draggable
  },
  props: {
    specs: {
      type: Array,
      default: () => [],
      validator: value => {
        if (value.length === 0) return true;
        return value.every(spec =>
          spec &&
          Array.isArray(spec.values) &&
          spec.values.every(v => typeof v === 'string' || typeof v === 'number')
        );
      }
    },
    skuData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      internalSpecs: [],
      skus: [],
      imgUploadUrl: process.env.VUE_APP_API_BASE_URL + '/upload/uploadImage',
      generatingSkus: false,
      batchDialog: {
        visible: false,
        title: '',
        label: '',
        value: 0,
        precision: 0,
        type: ''
      },
      skuMapCache: null // 用于缓存SKU查找的Map
    };
  },
  computed: {
    canReset() {
      return this.internalSpecs.length > 0 || this.skus.length > 0;
    },
    canGenerateSkus() {
      return this.validateSpecs();
    }
  },
  watch: {
    skuData: {
      handler(val) {
        this.processSkuData(val);
      },
      deep: true,
      immediate: true
    },
    specs: {
      handler(val) {
        if (val && val.length > 0) {
          this.internalSpecs = JSON.parse(JSON.stringify(val));
          this.skus = [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 数据处理方法
    processSkuData(val) {
      try {
        if (val && val.specs && Array.isArray(val.specs) && val.skus && Array.isArray(val.skus)) {
          this.internalSpecs = val.specs.map(spec => ({
            id: spec.id || 0,
            name: spec.name || '',
            values: (spec.values || []).map(v => v.value || ''),
            images: (spec.values || []).reduce((acc, cur) => {
              if (cur && cur.value) acc[cur.value] = cur.image;
              return acc;
            }, {}),
            rawValues: spec.values || []
          }));

          this.skus = val.skus.map(sku => ({
            ...sku,
            price: parseFloat(sku.price) || 0,
            market_price: parseFloat(sku.market_price) || 0,
            stock: parseInt(sku.stock) || 0,
            weight: parseFloat(sku.weight) || 0
          }));
        }
      } catch (error) {
        console.error('处理skuData出错:', error);
        this.internalSpecs = [];
        this.skus = [];
      }
    },

    // 规格验证方法
    validateSpecs() {
      return this.internalSpecs.length > 0 &&
        this.internalSpecs.every(spec => {
          if (!spec) return false;

          const values = spec.rawValues || spec.values || [];
          if (!Array.isArray(values)) return false;

          return spec.name &&
                 values.length > 0 &&
                 values.every(v => {
                   const value = (v && v.value) || v;
                   return value !== undefined && value !== null && value.toString().trim() !== '';
                 });
        });
    },

    // 生成SKU核心方法
    generateSkus() {
      if (!this.canGenerateSkus) {
        this.$message.error('请完善规格信息');
        return;
      }

      this.skuMapCache = null;
      this.generatingSkus = true;

      setTimeout(() => {
        try {
          const specValuesGroups = this.internalSpecs.map(spec => {
            const values = spec.rawValues || spec.values || [];

            return values.map(v => {
              if (typeof v === 'object' && v !== null) {
                return {
                  id: v.id || 0,
                  spec_id: spec.id || 0,
                  value: v.value || '',
                  image: v.image || (spec.images ? spec.images[v.value] : '')
                };
              }
              return {
                id: 0,
                spec_id: spec.id || 0,
                value: v || '',
                image: spec.images ? spec.images[v] : ''
              };
            });
          });

          const validGroups = specValuesGroups.filter(group => group.length > 0);
          if (validGroups.length !== this.internalSpecs.length) {
            throw new Error('存在空的规格值组');
          }

          const combinations = this.cartesianProduct(validGroups);

          this.skus = combinations.map(comb => {
            const existingSku = this.findMatchingSku(comb);

            if (existingSku) {
              return {
                ...existingSku,
                price: existingSku.price || 0,
                stock: existingSku.stock || 0,
                market_price: existingSku.market_price || 0
              };
            }

            return {
              id: 0,
              product_id: 0,
              spec_values: comb.map(item => item.value),
              price: 0,
              market_price: 0,
              stock: 0,
              code: this.generateSkuCode(comb),
              image: '',
              weight: 0,
              spec_ids: comb.map(item => item.id || 0).join(':')
            };
          });
        } catch (error) {
          console.error('生成SKU失败:', error);
          this.$message.error(`生成SKU失败: ${error.message}`);
        } finally {
          this.generatingSkus = false;
        }
      }, 50);
    },

    // SKU匹配方法（带缓存）
    findMatchingSku(comb) {
      if (!this.skuData?.skus || !Array.isArray(this.skuData.skus)) return null;

      try {
        const specKey = comb.map(item => {
          const value = (item && item.value) || item;
          return `${value}`.trim().toLowerCase();
        }).join('|');

        if (!this.skuMapCache) {
          this.skuMapCache = new Map();
          this.skuData.skus.forEach(sku => {
            if (sku.spec_values && Array.isArray(sku.spec_values)) {
              const key = sku.spec_values
                .map(v => `${v}`.trim().toLowerCase())
                .join('|');
              this.skuMapCache.set(key, sku);
            }
          });
        }

        return this.skuMapCache.get(specKey);
      } catch (error) {
        console.error('匹配SKU失败:', error);
        return null;
      }
    },

    // 笛卡尔积计算方法
    cartesianProduct(arr) {
      return arr.reduce((a, b) => {
        const result = [];
        a.forEach(x => {
          b.forEach(y => {
            result.push([...x, y]);
          });
        });
        return result;
      }, [[]]).filter(x => x.length > 0);
    },

    // 其他原有方法保持不变
    addSpec() {
      if (this.internalSpecs.length >= 5) {
        this.$message.warning('最多只能添加5个规格');
        return;
      }
      this.internalSpecs.push({
        id: 0,
        name: '',
        values: [],
        images: {},
        rawValues: []
      });
    },

    removeSpec(index) {
      this.internalSpecs.splice(index, 1);
      this.skus = [];
    },

    addSpecValue(specIndex) {
      const spec = this.internalSpecs[specIndex];
      if (spec.values.length >= 20) {
        this.$message.warning('每个规格最多只能添加20个值');
        return;
      }
      spec.values.push('');
      if (spec.rawValues) {
        spec.rawValues.push({
          id: 0,
          spec_id: spec.id || 0,
          value: '',
          image: ''
        });
      }
    },

    removeSpecValue(specIndex, valueIndex) {
      this.internalSpecs[specIndex].values.splice(valueIndex, 1);
      if (this.internalSpecs[specIndex].rawValues) {
        this.internalSpecs[specIndex].rawValues.splice(valueIndex, 1);
      }
      if (this.internalSpecs[specIndex].values.length === 0) {
        this.removeSpec(specIndex);
      }
    },

    validateSpecName(specIndex) {
      if (!this.internalSpecs[specIndex].name) {
        this.$message.error('规格名称不能为空');
        return false;
      }
      return true;
    },

    validateSpecValue(specIndex, valueIndex) {
      if (!this.internalSpecs[specIndex].values[valueIndex]) {
        this.$message.error('规格值不能为空');
        return false;
      }
      if (this.internalSpecs[specIndex].rawValues &&
          this.internalSpecs[specIndex].rawValues[valueIndex]) {
        this.internalSpecs[specIndex].rawValues[valueIndex].value =
          this.internalSpecs[specIndex].values[valueIndex];
      }
      return true;
    },

    handleSpecValueBlur(specIndex, valueIndex) {
      this.validateSpecValue(specIndex, valueIndex);
    },

    handleSpecImageSuccess(res, file, specIndex, valueIndex) {
      const imageUrl = this.$imageFull(res.data);
      const spec = this.internalSpecs[specIndex];
      const value = spec.values[valueIndex];

      this.$set(spec.images, value, imageUrl);

      if (spec.rawValues && spec.rawValues[valueIndex]) {
        this.$set(spec.rawValues[valueIndex], 'image', imageUrl);
      }

      this.$message.success('图片上传成功');
    },

    submitData() {
      const postData = {
        specs: this.internalSpecs.map(spec => ({
          id: spec.id || 0,
          name: spec.name,
          values: (spec.rawValues || spec.values).map((v, index) => ({
            id: spec.rawValues ? spec.rawValues[index].id : 0,
            spec_id: spec.id || 0,
            value: typeof v === 'object' ? v.value : v,
            image: spec.images ? spec.images[typeof v === 'object' ? v.value : v] : ''
          }))
        })),
        skus: this.skus.map(sku => ({
          id: sku.id || 0,
          product_id: sku.product_id || 0,
          spec_values: sku.spec_values,
          price: sku.price,
          market_price: sku.market_price,
          stock: sku.stock,
          code: sku.code,
          image: sku.image,
          weight: sku.weight,
          spec_ids: sku.spec_ids || this.getSpecIds(sku.spec_values)
        }))
      };

      this.$emit('skuRulChange', postData);
    },

    // 其他辅助方法...
    generateSkuCode(comb) {
      const prefix = comb.map(item => {
        const value = item.value || item;
        return value.toString().charAt(0).toUpperCase();
      }).join('');

      return `${prefix}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
    },

    getSpecIds(specValues) {
      return specValues.map((value, index) => {
        const spec = this.internalSpecs[index];
        if (!spec || !spec.rawValues) return 0;

        const valObj = spec.rawValues.find(v => v.value === value);
        return valObj ? valObj.id : 0;
      }).join(':');
    },

    batchSetPrice() {
      this.batchDialog = {
        visible: true,
        title: '批量设置价格',
        label: '价格(元)',
        value: 0,
        precision: 2,
        type: 'price'
      };
    },

    batchSetMarketPrice() {
      this.batchDialog = {
        visible: true,
        title: '批量设置划线价格',
        label: '价格(元)',
        value: 0,
        precision: 2,
        type: 'market_price'
      };
    },

    batchSetStock() {
      this.batchDialog = {
        visible: true,
        title: '批量设置库存',
        label: '库存',
        value: 0,
        precision: 0,
        type: 'stock'
      };
    },

    confirmBatchSet() {
      const { type, value } = this.batchDialog;
      this.skus.forEach(sku => {
        sku[type] = value;
      });
      this.batchDialog.visible = false;
      this.$message.success('批量设置成功');
    },

    resetData() {
      this.$confirm('确定要重置所有规格和SKU数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.internalSpecs = [];
        this.skus = [];
        this.$message.success('已重置所有数据');
      }).catch(() => {
        this.$message.info('已取消重置');
      });
    },

    handleSkuImageSuccess(res, file, skuIndex) {
      const imageUrl = res.data;
      this.skus[skuIndex].image = this.$imageFull(imageUrl);
      this.$message.success('图片上传成功');
    }
  },
  mounted() {
    // 初始化数据检查
    if (!Array.isArray(this.internalSpecs)) {
      this.internalSpecs = [];
    }
    if (!Array.isArray(this.skus)) {
      this.skus = [];
    }
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.multi-spec-container {
  padding: 20px;
}
.spec-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.spec-header {
  margin-bottom: 10px;
}
.spec-value-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.spec-image-preview {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}
.sku-image {
  width: 40px;
  height: 40px;
}
.generate-sku {
  margin: 20px 0;
}
.bt-fix {
  margin-top: 20px;
}
</style>
